//
//  STTools_RcImManger.m
//  GoldChampion
//
//  Created by coder on 2018/5/17.
//  Copyright © 2018年 stoneobs@icloud.com. All rights reserved.
//

#import "STTools_RcImManger.h"
#import<CommonCrypto/CommonDigest.h>
@interface STTools_RcImManger()<RCIMUserInfoDataSource,RCIMGroupInfoDataSource,RCIMConnectionStatusDelegate>
@property(nonatomic, strong) NSString                     *rcAppKey;/**< rcAppKey */
@property(nonatomic, strong) NSString                     *appSecret;/**< appSecret */
@end
@implementation STTools_RcImManger
+ (STTools_RcImManger *)manger{
    static STTools_RcImManger * manger = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manger = [STTools_RcImManger new];
    });
    return manger;
}

- (void)registerRcAppKey:(NSString *)rcAppKey appSecret:(NSString *)appSecret{
    [[RCIM sharedRCIM] initWithAppKey:rcAppKey];
    self.rcAppKey = rcAppKey;
    self.appSecret = appSecret;
    [RCIM sharedRCIM].userInfoDataSource = self;;
    [RCIM sharedRCIM].groupInfoDataSource = self;
//    [RCIM sharedRCIM].currentUserInfo = STTools_UserManger.defult.stoneobs_fun_get_loginedUser.userInfo;
    [RCIM sharedRCIM].enableMessageAttachUserInfo = YES;
    [RCIM sharedRCIM].connectionStatusDelegate = self;
    [RCIM sharedRCIM].enablePersistentUserInfoCache = YES;
}
- (void)logout{
    [[RCIM sharedRCIM] logout];
}
- (void)loginWithUserId:(NSString *)userId nickName:(NSString *)nickName iconUrl:(NSString *)iconUrl handle:(void (^)(NSString *))handle{
    if (![STTools_RcImManger manger].appSecret.length) {
        DDLogError(@"请先 registerRcAppKey");
        return;
    }
    nickName = nickName.length?nickName:@"";
    iconUrl = iconUrl.length?iconUrl:@"";
    
    RCUserInfo * info = [RCUserInfo new];
    info.userId = userId;
    info.name = nickName;
    info.portraitUri = iconUrl;
    
    
    [self.class fecthRCTokenWithUserID:userId nickName:nickName iconUrl:iconUrl handle:^(NSString *token) {
        //使用融云的IMKit登录方式

        
    }];
}
+ (void)fecthRCTokenWithUserID:(NSString *)userID nickName:(NSString *)nickName iconUrl:(NSString *)iconUrl handle:(void (^)(NSString *))handle{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.requestSerializer.timeoutInterval = 10;
    NSString * url = @"http://api.cn.ronghub.com/user/getToken.json";
    nickName = nickName.length?nickName:@"";
    iconUrl = iconUrl.length?iconUrl:@"";
    NSDictionary * dic = @{@"userId":userID,@"name":nickName,@"portraitUri":iconUrl};
    
    NSString * nonce = [self.class randromString];
    NSString * time = [self.class timeString];
    NSString * signature = [self.class sha1WithAppSecret:[STTools_RcImManger manger].appSecret nonce:nonce time:time];
    
    [manager.requestSerializer setValue:[STTools_RcImManger manger].rcAppKey forHTTPHeaderField:@"App-Key"];
    [manager.requestSerializer setValue:nonce forHTTPHeaderField:@"Nonce"];
    [manager.requestSerializer setValue:time forHTTPHeaderField:@"Timestamp"];
    [manager.requestSerializer setValue:signature forHTTPHeaderField:@"Signature"];
    
    
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json", @"text/plain", @"text/html", nil];

    
}
- (void)updateSendUserInfoWithName:(NSString *)nickname iconUrl:(NSString *)iconUrl{
    RCUserInfo * info = [RCIM sharedRCIM].currentUserInfo;
    info.name = nickname;
    info.portraitUri = iconUrl;
    [RCIM sharedRCIM].currentUserInfo = info;
    [RCIM sharedRCIM].enableMessageAttachUserInfo = YES;
}
#pragma mark --RCIMUserInfoDataSource
- (void)getUserInfoWithUserId:(NSString *)userId completion:(void (^)(RCUserInfo *userInfo))completion{
    // 更新数据
//    [TreeHoleUserDataController stoneobs_fun_fetchRCUserInfoWithUser_id:userId handle:^(RCUserInfo * info) {
////        [RCIM.sharedRCIM refreshUserInfoCache:info withUserId:userId];
//        if (completion) {
//            completion(info);
//        }
//    }];
    
    
}
#pragma mark --RCIMGroupInfoDataSource
- (void)getGroupInfoWithGroupId:(NSString *)groupId completion:(void (^)(RCGroup *groupInfo))completion{

}
#pragma mark --RCIMConnectionStatusDelegate
- (void)onRCIMConnectionStatusChanged:(RCConnectionStatus)status{
    if (status == ConnectionStatus_KICKED_OFFLINE_BY_OTHER_CLIENT) {
        //他端 登录
        [TMUtils.stoneobs_fun_get_currentTopController stoneobs_fun_st_showAlertTitle:@"系统检测到您的账号在其他设备登录，如果不是您本人操作，有可能您的密码已经泄露，请注意修改密码" message:@"" andWithBlock:^(NSString *name) {
            [[RCIMClient sharedRCIMClient] logout];
            [[STTools_UserManger defult] stoneobs_fun_removeUserPreferce];
            UIWindow * window =  UIApplication.sharedApplication.delegate.window;
            window.rootViewController = [[RTRootNavigationController alloc] initWithRootViewController:STTools_TabbarViewController.new];
            [window stoneobs_fun_st_showAnimationWithType:STAnimationTypecube_stoneobs_enum];
        }];

    }
}
#pragma mark --Private Method
+ (NSString*)randromString{
    NSInteger index = arc4random()%1000;
    return @(index).description;
}
+ (NSString*)timeString{
    NSInteger  num = [[NSDate stoneobs_fun_localCurrentDate] timeIntervalSince1970] * 1000;
    return @(num).debugDescription;
}
+ (NSString*)sha1WithAppSecret:(NSString*)appSecret  nonce:(NSString*)nonce time:(NSString*)time{
    
    NSString * input = [NSString stringWithFormat:@"%@%@%@",appSecret,nonce,time];
    const char *cstr = [input cStringUsingEncoding:NSUTF8StringEncoding];
    NSData *data = [NSData dataWithBytes:cstr length:input.length];
    
    uint8_t digest[CC_SHA1_DIGEST_LENGTH];
    CC_SHA1(data.bytes, (unsigned int)data.length, digest);
    NSMutableString *output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
    
    for(int i=0; i<CC_SHA1_DIGEST_LENGTH; i++) {
        [output appendFormat:@"%02x", digest[i]];
    }
    return output;
}

#pragma mark --Public
- (void)loginWithRToken:(NSString*)rtoken{

    
}

- (void)registerAllCustomModel{

    
}
@end

